﻿using System;
using System.ComponentModel;
using System.Threading;
using PostSharp.Aspects;
using Sapit.Attributes.Interfaces;

namespace Sapit.PostSharp.Attributes
{
    /// <summary>
    /// Apply this attribute to methods that should have timeout.
    /// </summary>
    [Serializable]
    public class TimeoutAttribute : MethodInterceptionAspect, ITimeout
    {
        /// <summary>
        /// Maximum number of milliseconds before throwing an exception
        /// </summary>
        public double TimeoutMilliseconds { get; set; }

        public override void OnInvoke(MethodInterceptionArgs args)
        {
            BackgroundWorker worker = new BackgroundWorker();
            worker.WorkerSupportsCancellation = true;
            worker.DoWork += (sender, e) =>
            {
                args.Proceed();
            };
            worker.RunWorkerAsync();
            DateTime startTime = DateTime.Now;
            DateTime maxEndTime = startTime.AddMilliseconds(TimeoutMilliseconds);
            while (worker.IsBusy && DateTime.Now < maxEndTime)
            {
                Thread.Sleep(50);
            }
            if (args.ReturnValue == null)
            {
                worker.CancelAsync();
                worker.Dispose();
                throw new TimeoutException(string.Format("Timeout expired. Operation took longer than {0} milliseconds.", TimeoutMilliseconds));
            }
        }
    }
}
